package com.lq.pc.httpclient;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class HttpClientDemo {

    private static String userName = "";
    private static String passwd = "cd3fff50e9c52ddc012775eb34c4a37bcc925a92d187c11b3bf9bd2264491b84";
    private static String redirectURL = "http://www.renren.com/465530468/profile?v=info_timeline";
    private static String renRenLoginURL = "http://www.renren.com/PLogin.do";
    private static HttpResponse response;
    private static CloseableHttpClient httpDefault = HttpClients.createDefault();

    public static void main(String[] args) {

        HttpPost httpPost = new HttpPost(renRenLoginURL);
        List<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("origURL", "http://www.renren.com/967948816"));
        list.add(new BasicNameValuePair("email", "13054290269"));
        list.add(new BasicNameValuePair("domain", "renren.com"));
        list.add(new BasicNameValuePair("key_id", "1"));
        list.add(new BasicNameValuePair("captcha_type", "web_login"));
        list.add(new BasicNameValuePair("password", passwd));
        list.add(new BasicNameValuePair("rkey", "6d7d2086ddd44c39ae683b6d93c0a39f"));

        httpPost.setHeader("Accept", "text/html,application/xhtml+xml," +
                "application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, sdch, br");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36" +
                " (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            response = httpDefault.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            log.info("status code is {}", statusCode);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("-------------------------------result{}", result);

            String refUrl = response.getFirstHeader("Location").getValue();
            HttpGet httpGet = new HttpGet(refUrl);
            CloseableHttpResponse execute = httpDefault.execute(httpGet);
            String res = EntityUtils.toString(execute.getEntity(), "utf-8");
            log.info("-------------------------------res{}", res);

            log.info("result{}", result);

            Document document = Jsoup.connect(refUrl).timeout(100000).get();
            Elements links = document.select("a[href]");
            Elements media = document.select("[src]");
            Elements imports = document.select("link[href]");

            print("\nMedia: (%d)", media.size());
            for (Element src : media) {
                if (src.tagName().equals("img"))
                    print(" * %s: <%s> %sx%s (%s)",
                            src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
                            trim(src.attr("alt"), 20));
                else
                    print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
            }

            print("\nImports: (%d)", imports.size());
            for (Element link : imports) {
                print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel"));
            }

            print("\nLinks: (%d)", links.size());
            for (Element link : links) {
                print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpDefault.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }

    private static String trim(String s, int width) {
        if (s.length() > width)
            return s.substring(0, width - 1) + ".";
        else
            return s;
    }

}
